package com.hyj.app.demo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ProcessManagerService extends Service {
    private final IBinder binder = new LocalBinder();
    private final Map<String, Boolean> runningProcesses = new ConcurrentHashMap<>();
    private final RemoteCallbackList<ProcessObserver> observers = new RemoteCallbackList<>();

    public class LocalBinder extends Binder {
        ProcessManagerService getService() {
            return ProcessManagerService.this;
        }
    }

    public void registerObserver(ProcessObserver observer) {
        observers.register(observer);
    }

    public boolean isProcessRunning(String name) {
        return runningProcesses.containsKey(name) && Boolean.TRUE.equals(runningProcesses.get(name));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    // 通知所有观察者
    private void notifyObservers(String processName, boolean isCreated) {
        runningProcesses.put(processName, isCreated);
        final int N = observers.beginBroadcast();
        for (int i = 0; i < N; i++) {
            try {
                ProcessObserver observer = observers.getBroadcastItem(i);
                if (isCreated) {
                    observer.onProcessCreated(processName);
                } else {
                    observer.onProcessDestroyed(processName);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        observers.finishBroadcast();
    }
}